package com.webtest.controller;

import com.webtest.dao.UserMapper;
import com.webtest.entity.User;
import com.webtest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.Date;

@Controller
public class AboutController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/alter")
    public String toAboutMe(HttpSession session, Model model){
        User user = (User)session.getAttribute("user");
        User userById = userService.findUserById(user.getId());
        model.addAttribute("userById",userById);
        return "about";
    }
    @RequestMapping("/addMoney")
    @ResponseBody
    public String addMoney(HttpSession session,User user, Model model){
        User userNow = (User)session.getAttribute("user");
        user.setId(userNow.getId());
        userMapper.addMoney(user);
//        attributes.addFlashAttribute("message", "成功");
//        model.addAttribute("userById",user.getId());
        return "成功";
    }
    @RequestMapping("/addVip")
    @ResponseBody
    @Transactional
    public String addVip(HttpSession session,User user, Model model){
        User userNow = (User)session.getAttribute("user");
        user.setId(userNow.getId());
        //查询用户目前信息
        User now = userMapper.findUserById(userNow.getId());
        Date vipTime = new Date();
        if(now.getOuttime() != null &&now.getOuttime().getTime() > new Date().getTime()){
            vipTime = now.getOuttime();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(vipTime);
        calendar.add(Calendar.MONTH,user.getVip());

        user.setOuttime(calendar.getTime());

        //这里user 的vip 充当vip 月数
        int add = user.getVip();
        double feiyong = 0;
        if(add>=3 && add<=6){
           feiyong = add * 30 *0.9;
        }else if(add >6){
            feiyong = add * 30 *0.8;
        }else{
            feiyong  = add * 30;
        }
        if(now.getMoney() < feiyong){
            return "金额不足";
        }
        user.setMoney(-feiyong);

        userMapper.addMoney(user);
        userMapper.addVip(user);
//        attributes.addFlashAttribute("message", "成功");
//        model.addAttribute("userById",user.getId());
        return "成功";
    }
}
